import os
import h5py
import random
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt


lowess = sm.nonparametric.lowess
csvData = pd.read_csv('.\kneepoint\Batch3KneePoint.csv', header=None)  # header=None是去掉表头部分
csvData = csvData.iloc[:, 0]
allKneePoint = np.array(csvData).astype(int)

def LoadQandV(filename):
    f = h5py.File(filename)
    list(f.keys())
    batch = f['batch']
    list(batch.keys())
    # random.shuffle(cell)
    for o in range(0, 1):  # 取前4节电池
        o = 0
        print("cell: ", o)
        cycles = f[batch['cycles'][o, 0]]
        # 3×180 得到三个cv时间段存到list中
        zero2one_period_list = []
        # 得到三个cc时间段存到list中
        four_cc_period_list = []
        # 得到三个cv时间段存到list中
        four2zero_period_list = []
        t2v = []
        q2qd = []
        t_to_i = []
        ts = []
        tim_I = []  # 后三个阶段(cv cc cv)

        kneePoint = allKneePoint[o]

        # 获取距离膝点超过或少于100的周期的数据
        # 随机获取膝点前的某个循环的数据
        r = random.random()
        if r >= 0.5:
            if kneePoint - 150 > 0:
                cycle = random.randint(20, kneePoint - 150)
            else:
                cycle = random.randint(kneePoint - 70, kneePoint)
        if r < 0.5:
            cycle = random.randint(kneePoint - 70, kneePoint)
        print('r:' + str(r))
        print('cycle:' + str(cycle))
        print('kneepoint:' + str(kneePoint))
        # for i in range(cycle - 2, cycle + 1):
        for i in range(cycle):
            zero2one_TIM = []
            four_cc_TIM = []
            four2zero_TIM = []
            slope_list = []
            I = np.hstack((f[cycles['I'][i, 0]][()]))
            print("I_length: ", len(I))
            t = np.hstack((f[cycles['t'][i, 0]][()]))

            V = np.hstack((f[cycles['V'][i, 0]][()]))
            Qd = np.hstack((f[cycles['Qd'][i, 0]][()]))

            for k in range(0, 600):
                t_max = t[-1]
                t_min = t[0]
                tdev = (t_max - t_min) / 600
                t_need = t[0] + tdev * k
                idx = (np.abs(t - t_need)).argmin()
                t_to_i.append(I[idx])
                ts.append(t[idx])

                t2v.append(V[idx])
                q2qd.append(Qd[idx])

            for temp in range(len(t_to_i)):
                slope = (t_to_i[temp] - t_to_i[temp - 1]) / (ts[temp] - ts[temp - 1])
                # print(round(slope, 4))
                slope = float(round(slope, 3))
                slope_list.append(slope)
            # print(new_slope_list)
            # print(len(new_slope_list))

            for k in range(0, 600):
                t_max = t[-1]
                t_min = t[0]
                tdev = (t_max - t_min) / 600
                t_need = t[0] + tdev * k
                idx = (np.abs(t - t_need)).argmin()
                idx_next = (np.abs(t - (t[0] + tdev * (k + 10)))).argmin()
                # slope_list = slope_list[0:600]
                if (-4.1 <= I[idx] <= -3.8) & (-0.5 <= slope_list[k] <= 0.5):
                    tim_I.append(I[idx])
                    four_cc_TIM.append(t[idx])

                elif (0.005 <= I[idx] <= 1.005) & (t[idx] != 0) & (I[idx] - I[idx_next] >= 0.01) & (
                        -5 <= slope_list[k] <= 0.5):
                    tim_I.append(I[idx])
                    zero2one_TIM.append(t[idx])
                    # print("在0到1之间的数据:", I[idx])

                elif (-3.6 <= I[idx] <= -0.01) & (-0.5 <= slope_list[k]):
                    tim_I.append(I[idx])
                    four2zero_TIM.append(t[idx])

                else:
                    tim_I.append(0)

            # plt.plot(t2v, label='V')
            # plt.plot(q2qd, label='Q')
            # plt.plot(t_to_i, label='I')
            # plt.legend()
            # plt.grid()
            # plt.show()

            # print("************************************")
            # print("************有关时间600结束***********")
            # print("************************************\n")

            '''
            zero2one_period = zero2one_TIM[-1] - zero2one_TIM[0]
            four_cc_period = four_cc_TIM[-1] - four_cc_TIM[0]
            four2zero_period = four2zero_TIM[-1] - four2zero_TIM[0]
            '''

            zero2one_period = zero2one_TIM[-1] - zero2one_TIM[0]
            four_cc_period = four_cc_TIM[-1] - zero2one_TIM[-1]
            four2zero_period = four2zero_TIM[-1] - four_cc_TIM[-1]

            zero2one_period_list.append(zero2one_period)
            # z2o_aver = np.mean(zero2one_period_list)
            # list1.append(z2o_aver)

            four_cc_period_list.append(four_cc_period)
            # fourcc_aver = np.mean(four_cc_period_list)
            # list2.append(fourcc_aver)

            four2zero_period_list.append(four2zero_period)
            # f2z_aver = np.mean(four2zero_period_list)
            # list3.append(f2z_aver)

            # print("cv: ", zero2one_TIM[-1], zero2one_TIM[0], "\n")
            # print("4cc: ", four_cc_TIM[-1], four_cc_TIM[0], "\n")
            # print("cv", four2zero_TIM[-1], four2zero_TIM[0], "\n")
            # print(zero2one_period, four_cc_period, four2zero_period, "\n")

            print("***************************************")
            print("*第", o, "节电池, 共计", cycle - 2, "次循环,第", i+1, "次结束*******")
            print("*************************************\n")

        list1 = zero2one_period_list
        list2 = four_cc_period_list
        list3 = four2zero_period_list

        print("*************循环结束*****************")
        print("************电池中第", o+1, "节结束********")
        print("*************************************\n")

        '''
        list3_percentile_85 = np.percentile(list3, 80)
        list3_lim = np.clip(list3, a_min=None, a_max=list3_percentile_85)
        print("list3_lim: ", list3_percentile_85)
        list1_percentile_85 = np.percentile(list1, 90)
        list1_lim = np.clip(list1, a_min=None, a_max=list1_percentile_85)
        print("list1_lim: ", list1_percentile_85)
        '''
        list1_text = np.linspace(0, 3, len(list1))
        list2_text = np.linspace(7, 10, len(list1))
        list3_text = np.linspace(12, 15, len(list1))

        plt.figure()
        plt.scatter(list1_text, list1, label='One')
        plt.scatter(list2_text, list2, label='Two')
        plt.scatter(list3_text, list3, label='Three')
        plt.legend()

        path = "D:\PycharmProjects\My_project\LSTM"
        name1 = f"{o}_cell_data1.txt"
        name2 = f"{o}_cell_data2.txt"
        name3 = f"{o}_cell_data3.txt"
        list_filename1 = os.path.join(path, name1)
        list_filename2 = os.path.join(path, name2)
        list_filename3 = os.path.join(path, name3)
        print(list_filename1)
        print(list_filename2)
        print(list_filename3)

        # np.savetxt(list_filename1, list1, fmt='%.5f')
        # np.savetxt(list_filename2, list2, fmt='%.5f')
        # np.savetxt(list_filename3, list3, fmt='%.5f')
        # plt.show()

LoadQandV('2019-01-24_batchdata_updated_struct_errorcorrect.mat')
